package com.cb.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.spzx.manager.mapper.SysUserRoleMapper;
import com.cb.spzx.manager.service.SysRoleService;
import com.cb.spzx.manager.mapper.SysRoleMapper;
import com.cb.spzx.model.dto.system.SysRoleDto;
import com.cb.spzx.model.entity.system.SysRole;
import com.cb.spzx.model.entity.system.SysRoleUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author lenovo
* @description 针对表【sys_role(角色)】的数据库操作Service实现
* @createDate 2024-04-08 16:45:40
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public IPage<SysRole> findByPage(SysRoleDto sysRoleDto, Page<SysRole> sysRolePage) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StrUtil.isEmpty(sysRoleDto.getRoleName()),SysRole::getRoleName,sysRoleDto.getRoleName());
        queryWrapper.orderByDesc(SysRole::getCreateTime);
        return baseMapper.selectPage(sysRolePage, queryWrapper);
    }

    @Override
    public int saveSysRole(SysRole sysRole) {
        return baseMapper.insert(sysRole);
    }

    @Override
    public int updateSysRole(SysRole sysRole) {
        sysRole.setUpdateTime(new Date());
        return baseMapper.updateById(sysRole);
    }

    @Override
    public int deleteById(Long roleId) {
        return baseMapper.deleteById(roleId);
    }

    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        //查询所有角色
        List<SysRole> sysRoles = baseMapper.selectList(null);
        // 查询当前登录用户的角色数据
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getUserId,userId);
        List<SysRoleUser> sysRoleUsers = sysUserRoleMapper.selectList(queryWrapper);
        List<Long> roleIds = new ArrayList<>();
        for (SysRoleUser sysRoleUser : sysRoleUsers) {
            roleIds.add(sysRoleUser.getRoleId());
        }
        Map<String,Object> map=new HashMap<>();
        map.put("allRolesList",sysRoles);
        map.put("sysUserRoles",roleIds);
        return map;
    }
}




